﻿package com.Base.ResBase
{
	import flash.display.Loader;
	import flash.net.URLRequest;
	import flash.events.*;
	
	import com.Base.Logger.Logger;
	
	public class ResLoader
	{
		//单件
		public static function get instance():ResLoader
		{
			if (! _instance)
			{
				_instance = new ResLoader(new SingletonEnforcer());
			}
			
			return _instance;
		}
		
		//构造函数
		public function ResLoader(enforcer:SingletonEnforcer):void
		{
			_resAddress = "";
		}
		
		//设置load完成后的回调
		public function set onLoadComplete(callback:Function):void
		{
			_onLoadComplete = callback;
			_loader = new Loader();
		}
		
		//设置资源地址
		public function set resAddress(address:String):void
		{
			_resAddress = address;
		}
		
		//开始load资源
		public function load():void
		{
			var urlReq:URLRequest = new URLRequest(_resAddress);

			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
			_loader.load(urlReq);
		}
		
		//资源load完毕时的处理，需重载
		protected function processResource():void
		{
			Logger.throwError("ResLoader::processResource()-->Abstract method!");
		}
		
		//load出错
		private function onError(e:IOErrorEvent):void
		{
			_loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onError);
			_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete);
			
			Logger.output("Error occured while loading " + _resAddress + " !");
		}
		
		//load完毕
		private function onComplete(e:Event):void
		{
			_loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onError);
			_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete);
			
			if (null == _onLoadComplete)
			{
				Logger.throwError("ResLoader::onComplete()-->Null callback!");
				return;
			}
			
			processResource();
			_onLoadComplete();
		}
		
		private static var _instance:ResLoader;
		
		private var _onLoadComplete	:Function;
		private var _resAddress		:String;
		private var _loader			:Loader;
	}	
}

class SingletonEnforcer
{
	
}